<?php

class Common_Chart_Factory_FromDataTable_SingleColumn 
    extends Common_Chart_Factory_FromDataTable 
{
    
    public function create($enm_chart_type, $arr_options = array()) {
    
        if (!$this->issetDataTable() || !$this->getDataTable()->hasData()) {
            return null;
        }
        
        $obj_chart = null;

        $str_column_values = isset($arr_options['column_for_values'])
            ? $arr_options['column_for_values']
            : 'value';
        
        $str_column_labels = isset($arr_options['column_for_labels']) 
            ? $arr_options['column_for_labels'] 
            : 'label';
            
        $bln_include_zero_values = isset($arr_options['include_zero_values'])
            ? (boolean) $arr_options['include_zero_values']
            : true;

        $arr_chart_data = array();
        $arr_chart_labels = array();

        $arr_datatable_data = $this->getDataTable()->toArray();
        
        $arr_sort_columns = isset($arr_options['columns_to_sort'])
            ? $arr_options['columns_to_sort']
            : null;
            
        if(!empty($arr_sort_columns)) {
            Utility_SortFunctions::sort($arr_datatable_data, $arr_sort_columns);
        }
        
        $int_limit = isset($arr_options['limit'])
            ? (int) $arr_options['limit']
            : null;
            
        if(!empty($int_limit)) {
            $arr_datatable_data = array_slice($arr_datatable_data, 0, $int_limit);
        }

        foreach ($arr_datatable_data as $arr_row) {
            
            $num_value = (
                isset($arr_row[$str_column_values]) && 
                is_numeric($arr_row[$str_column_values])
            )
                ? $arr_row[$str_column_values] 
                : null;

            $str_label = isset($arr_row[$str_column_labels]) 
                ? $arr_row[$str_column_labels] 
                : null;
                
            if (
                !is_null($num_value) &&
                (
                    ($num_value != 0) ||
                    (
                        ($num_value == 0) &&
                        $bln_include_zero_values
                    )
                )
            ) {
                
                $arr_chart_data[]   = $num_value;
                $arr_chart_labels[] = $str_label;
                
            }
        }
        
        if(!empty($arr_chart_data)) {

            $obj_chart = parent::create($enm_chart_type, $arr_options);
            if(!is_null($obj_chart)) {
                $obj_chart->bind($arr_chart_data, $arr_chart_labels);
            }

        }

        return $obj_chart;
    
    }

}
